package com.zuorenke.rabbit;

import com.zuorenke.exception.InternalErrorCst;
import com.zuorenke.exception.InternalException;
import com.zuorenke.exception.Validation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * @author Z.R.K
 * @description
 * @create 2019-05-21 09:09:50
 **/
@Slf4j
public class RabbitMQSender  implements MessageSender, InitializingBean, ApplicationContextAware {
	
	private static final String DEFAULT_RABBIT_TEMPLATE_BEAN_NAME = "amqpTemplate";
	private String exchange;
	private String routingKey;
	private ApplicationContext applicationContext;
	private RabbitTemplate rabbitTemplate;
	
	public RabbitMQSender(String exchange, String routingKey){
		this.exchange = exchange;
		this.routingKey = routingKey;
	}
	
	@Override
	public void send(Object object) {
		Validation.notNull(object, "消息对象为空");
		try {
			rabbitTemplate.convertAndSend(exchange, routingKey, object);
		} catch (Exception e) {
			log.error("RabbitMQSender send message fail", e);
			throw new InternalException(InternalErrorCst.RABBITMQ_ERROR, e);
		}
		
	}
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) {
		this.applicationContext = applicationContext;
	}
	
	@Override
	public void afterPropertiesSet() throws Exception {
		if (this.rabbitTemplate == null) {
			if (applicationContext.containsBean(DEFAULT_RABBIT_TEMPLATE_BEAN_NAME)) {
				this.rabbitTemplate = applicationContext.getBean(DEFAULT_RABBIT_TEMPLATE_BEAN_NAME, RabbitTemplate.class);
			} else {
				this.rabbitTemplate = applicationContext.getBean(RabbitTemplate.class);
			}
		}
	}
}
